<?php

namespace App\Listeners;

use App\Models\SystemLog;
use App\Models\User;

/**
 * 用户事件订阅者
 * Author: Albert3306
 * Date: 2020/6/12
 * @package App\Listeners
 */
class UserEventSubscriber
{
    /**
     * 处理用户登录事件
     * Author: Albert3306
     * Date: 2020/6/12
     * @param $event
     */
    public function userLogin($event) {
        $user = $event->user;

        // 记录登录日志
        $log = [
            'user_id' => $user->id,
            'url'     => url('/admin/login'),
            'type'    => 'session',
            'content' => '管理员：' . $user->username . '【' . $user->nickname . '】 登录系统。'
        ];

        $systemLog = New SystemLog();
        $systemLog->write($log);

        // 更新登录数据
        $user->login = $user->login + 1;
        $user->last_login_ip = app('request')->ip();
        $user->last_login_at = date('Y-m-d H:i:s');
        $user->save();
    }

    /**
     * 处理用户注销事件
     * Author: Albert3306
     * Date: 2020/6/12 0012
     * @param $event
     */
    public function userLogout($event) {
        $user = $event->user;

        // 记录登出日志
        $log = [
            'user_id' => $user->id,
            'url'     => url('/admin/logout'),
            'type'    => 'session',
            'content' => '管理员：' . $user->username . '【' . $user->nickname . '】 登出系统。',
        ];

        $systemLog = New SystemLog();
        $systemLog->write($log);
    }

    /**
     * 为订阅者注册监听器
     * Author: Albert3306
     * Date: 2020/6/12
     * @param $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'App\Events\UserLogin',
            'App\Listeners\UserEventSubscriber@userLogin'
        );

        $events->listen(
            'App\Events\UserLogout',
            'App\Listeners\UserEventSubscriber@userLogout'
        );
    }
}
